﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ReferralTracker.BusinessObjects.Infrastructure {
    public class ReferralTrackerSession {
        const string SESSION_NAME = "currentsession";
        static ISession _session = null;
        static bool _localMode = false;

        public static ISession CurrentSession {
            get {
                ISession retVal = null;

                if (_localMode) {
                    retVal = _session;
                }
                else {
                    var webSession = HttpContext.Current.Session;

                    retVal = (ISession)webSession[SESSION_NAME];
                }

                return retVal;
            }
        }

        static ReferralTrackerSession() {
            _localMode = (HttpContext.Current == null);
        }

        public static ISession Open() {
            ISession retVal = null;

            if (_localMode) {
                if (_session == null) _session = ReferralTrackerApplication.Resolve<ISession>();
                retVal = _session;
            }
            else {
                var webSession = HttpContext.Current.Session;
                ISession session = null;

                if (webSession[SESSION_NAME] == null) {
                    session = ReferralTrackerApplication.Resolve<ISession>();
                    session.OnClose += new EventHandler(Session_OnClose);
                    webSession[SESSION_NAME] = session;
                }
                else {
                    session = (ISession)webSession[SESSION_NAME];
                }

                retVal = session;
            }

            return retVal;
        }

        public static ISession Create() {
            return ReferralTrackerApplication.Resolve<ISession>();
        }

        static void Session_OnClose(object sender, EventArgs e) {
            var session = (ISession)sender;

            if (_localMode) {
                _session = null;
            }
            else {
                var webSession = HttpContext.Current.Session;

                webSession.Remove(SESSION_NAME);
            }
            session.Dispose();
        }
    }
}
